/*
 * Copyright (c) 2017. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
 * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan.
 * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna.
 * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus.
 * Vestibulum commodo. Ut rhoncus gravida arcu.
 */

package com.esir.android;

import android.app.AppOpsManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;

import java.util.UUID;

import io.esirong.ActivityManager;


/**
 * AppUtil 应用的 系统的，设备的工具
 * Created by 黄嵘才(HuangRC) on 2017/10/19.
 */

public class AppUtil {
    private static final String TAG = AppUtil.class.getSimpleName();

    private AppUtil() {
    }

    /**
     * Return pseudo unique ID
     * 通过拼接ROM版本、制造商、CPU型号、以及其他硬件信息来实现这一点
     *
     * @return ID
     */
    public static String getUniqueID(Context context) {
        String id1 = "";
        try {
            id1 = getSerial();
        } catch (Exception exception) {
            //do nothing
        }
        String id3 = getPseudoID();
        String id = id1 + id3;
        return new UUID(id.hashCode(), id3.hashCode()).toString();
    }

    public static String getSerial() {
        try {
            return Build.class.getField("SERIAL").get(null).toString();
        } catch (Exception e) {
            return "";
        }
    }

    @NonNull
    public static String getPseudoID() {
        return Build.BOARD
                + Build.BRAND
                + Build.DEVICE
                + Build.MANUFACTURER
                + Build.MODEL
                + Build.PRODUCT;
    }

    /**
     * 获取当前APP的版本号
     *
     * @param context 应用上下文
     * @return 版本号
     */
    public static long versionCode(@NonNull Context context) {
        try {
            PackageManager pm = context.getPackageManager();
            // getPackageName()是你当前类的包名，0代表是获取版本信息
            PackageInfo packInfo = pm.getPackageInfo(context.getPackageName(), 0);
            return packInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            return -1;
        }
    }

    /**
     * 获取当前APP的版本名
     *
     * @param context 应用上下文
     * @return 版本名
     */
    public static String versionName(@NonNull Context context) {
        try {
            PackageManager pm = context.getPackageManager();
            // getPackageName()是你当前类的包名，0代表是获取版本信息
            PackageInfo packInfo = pm.getPackageInfo(context.getPackageName(), 0);
            return packInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            return "";
        }
    }

    /**
     * 获取当前手机系统版本号
     *
     * @return 系统版本号
     */
    public static String getSystemVersion() {
        return Build.DISPLAY;
        //return android.os.Build.VERSION.RELEASE;

    }


    /**
     * 获取手机型号
     *
     * @return 手机型号
     */
    public static String getSystemModel() {
        return Build.MODEL;
    }

    /**
     * 获取手机厂商
     *
     * @return 手机厂商
     */
    public static String getDeviceBrand() {
        return Build.BRAND;
    }

    /**
     * 退出应用
     */
    public static void exitApp() {
        try {
            ActivityManager.INSTANCE.finishAll();
            android.os.Process.killProcess(android.os.Process.myPid());
            System.exit(0);
        } catch (Exception e) {
            //ignore
        }
    }

    /**
     * 查看使用情况权限
     * 趺转到Android系统授权本APP查看使用情况
     * <p>
     * uses-permission
     * android:name="android.permission.PACKAGE_USAGE_STATS"
     * tools:ignore="ProtectedPermissions"
     */
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public static void tryStartPackageUsageState(@NonNull Context context) {
        Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
        context.startActivity(intent);
    }


    // To check if service is enabled
    public static boolean isAccessibilitySettingsOn(Context mContext) {
        int accessibilityEnabled = 0;
        final String service = "io.silvrr.app/io.silvrr.app.service.MainLockerService";
        boolean accessibilityFound = false;
        try {
            accessibilityEnabled = Settings.Secure.getInt(
                    mContext.getApplicationContext().getContentResolver(),
                    Settings.Secure.ACCESSIBILITY_ENABLED);
            Log.v(TAG, "accessibilityEnabled = " + accessibilityEnabled);
        } catch (Settings.SettingNotFoundException e) {
            Log.e(TAG, "Error finding setting, default accessibility to not found: "
                    + e.getMessage());
        }
        TextUtils.SimpleStringSplitter mStringColonSplitter = new TextUtils.SimpleStringSplitter(':');

        if (accessibilityEnabled == 1) {
            Log.v(TAG, "***ACCESSIBILIY IS ENABLED*** -----------------");
            String settingValue = Settings.Secure.getString(
                    mContext.getApplicationContext().getContentResolver(),
                    Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
            if (settingValue != null) {
                TextUtils.SimpleStringSplitter splitter = mStringColonSplitter;
                splitter.setString(settingValue);
                while (splitter.hasNext()) {
                    String accessabilityService = splitter.next();

                    Log.v(TAG, "-------------- > accessabilityService :: " + accessabilityService);
                    if (accessabilityService.equalsIgnoreCase(service)) {
                        Log.v(TAG, "We've found the correct setting - accessibility is switched on!");
                        return true;
                    }
                }
            }
        } else {
            Log.v(TAG, "***ACCESSIBILIY IS DISABLED***");
        }

        return accessibilityFound;
    }

    public static boolean isGetUsageStatsOn(Context context) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return true;
        }
        final AppOpsManager appOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
        int mode = appOps.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS,
                android.os.Process.myUid(), context.getPackageName());
        if (mode == AppOpsManager.MODE_ALLOWED) {
            return true;
        }
        return false;
    }
}
